<?php
require_once 'Database.php';

/**
 * 商品管理类
 */
class ProductManager {
    private $db;

    public function __construct() {
        $this->db = Database::getInstance();
    }

    /**
     * 创建商品
     */
    public function createProduct($name, $description, $price, $stock, $image = '') {
        $sql = "INSERT INTO products (name, description, price, stock, image, created_at, updated_at) 
                VALUES (?, ?, ?, ?, ?, NOW(), NOW())";
        
        return $this->db->query($sql, [$name, $description, $price, $stock, $image]);
    }

    /**
     * 添加商品 (createProduct的别名)
     */
    public function addProduct($name, $description, $price, $stock, $image = '') {
        return $this->createProduct($name, $description, $price, $stock, $image);
    }

    /**
     * 更新商品
     */
    public function updateProduct($id, $name, $description, $price, $stock, $status = 1, $image = '') {
        $sql = "UPDATE products SET name = ?, description = ?, price = ?, stock = ?, status = ?, image = ?, updated_at = NOW() 
                WHERE id = ?";
        
        return $this->db->query($sql, [$name, $description, $price, $stock, $status, $image, $id]);
    }

    /**
     * 减少商品库存
     */
    public function decreaseStock($productId, $quantity = 1) {
        $sql = "UPDATE products SET stock = stock - ?, updated_at = NOW() WHERE id = ? AND stock >= ?";
        return $this->db->query($sql, [$quantity, $productId, $quantity]);
    }

    /**
     * 增加商品库存
     */
    public function increaseStock($productId, $quantity = 1) {
        $sql = "UPDATE products SET stock = stock + ?, updated_at = NOW() WHERE id = ?";
        return $this->db->query($sql, [$quantity, $productId]);
    }

    /**
     * 获取所有商品
     */
    public function getAllProducts($onlyActive = false) {
        $sql = "SELECT * FROM products";
        if ($onlyActive) {
            $sql .= " WHERE status = 1";
        }
        $sql .= " ORDER BY created_at DESC";
        return $this->db->query($sql);
    }

    /**
     * 获取商品统计信息
     */
    public function getProductStatistics()
    {
        $sql = "SELECT 
                COUNT(*) as total_products,
                SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as active_products,
                SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as inactive_products,
                SUM(stock) as total_stock,
                AVG(price) as avg_price
                FROM products";
        
        $result = $this->db->query($sql);
        return !empty($result) ? $result[0] : [
            'total_products' => 0,
            'active_products' => 0,
            'inactive_products' => 0,
            'total_stock' => 0,
            'avg_price' => 0
        ];
    }

    /**
     * 根据ID获取商品
     */
    public function getProductById($id)
    {
        $sql = "SELECT * FROM products WHERE id = ?";
        $result = $this->db->query($sql, [$id]);
        return !empty($result) ? $result[0] : null;
    }

    /**
     * 删除商品
     */
    public function deleteProduct($id) {
        $sql = "DELETE FROM products WHERE id = ?";
        return $this->db->query($sql, [$id]);
    }

    /**
     * 检查商品库存
     */
    public function checkStock($id, $quantity = 1) {
        $product = $this->getProductById($id);
        return $product && $product['stock'] >= $quantity;
    }

    /**
     * 搜索商品
     */
    public function searchProducts($keyword) {
        $sql = "SELECT * FROM products WHERE (name LIKE ? OR description LIKE ?) AND status = 1 ORDER BY created_at DESC";
        $searchTerm = "%{$keyword}%";
        return $this->db->query($sql, [$searchTerm, $searchTerm]);
    }

    /**
     * 获取热门商品
     */
    public function getPopularProducts($limit = 10) {
        $sql = "SELECT p.*, COUNT(o.id) as order_count 
                FROM products p 
                LEFT JOIN orders o ON p.id = o.product_id 
                WHERE p.status = 1 
                GROUP BY p.id 
                ORDER BY order_count DESC, p.created_at DESC 
                LIMIT ?";
        return $this->db->query($sql, [$limit]);
    }

    /**
     * 更新商品状态
     */
    public function updateProductStatus($id, $status) {
        $sql = "UPDATE products SET status = ?, updated_at = NOW() WHERE id = ?";
        return $this->db->query($sql, [$status, $id]);
    }
}

// 处理AJAX请求
if (isset($_GET['action']) && $_GET['action'] === 'get_product' && isset($_GET['id'])) {
    header('Content-Type: application/json');
    
    $productManager = new ProductManager();
    $product = $productManager->getProductById($_GET['id']);
    
    if ($product) {
        echo json_encode([
            'success' => true,
            'product' => $product
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => '商品不存在'
        ]);
    }
    exit;
}
?>
